package com.campus.customer.controller;

import com.campus.common.bean.common.Resp;
import com.campus.customer.bean.WechatServerValidation;
import com.campus.customer.service.WechatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@Slf4j
@RestController
@Api(tags = "微信小程序官方API对接接口", produces = "application/json")
public class WechatController {


    @Value(value = "${wechat.token}")
    private String weChatToken;

    @Autowired
    private WechatService wechatService;



    @ApiOperation(value = "验证消息是否来自微信服务器")
    @GetMapping("/v1.0/wechatValidation")
    public String wechatValidation(@RequestParam String signature, @RequestParam String timestamp,
                                              @RequestParam String nonce, @RequestParam String echostr) {
        boolean isValidation = WechatServerValidation.validateSignature(weChatToken, signature, timestamp, nonce);

        log.info("验证消息是否通过：{}", Optional.of(isValidation).orElse(Boolean.FALSE));

        if(isValidation){
            return echostr;
        }else{
            return "validate fail";
        }

    }

    @ApiOperation(value = "获取小程序全局唯一后台接口调用凭据")
    @GetMapping("/v1.0/getAccessToken")
    public Resp<String> getAccessToken() {
        String accessToken = wechatService.getAccessToken();

        if(StringUtils.isBlank(accessToken)){
            return Resp.error("获取AccessToken失败");
        }

        return Resp.success(accessToken);
    }

}
